package gu.sql2java.velocity;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import com.google.common.base.Strings;

import net.gdface.utils.SimpleLog;

public class TemplateGenerator {

	/**
	 * Velocity引擎初始化
	 * 
	 * @param vprops
	 *            初始化参数,为{@code null}使用默认参数
	 */
	public static void init(Properties vprops) {
		if (null == vprops) {
			vprops = new Properties();
			/** 设置velocity默认的初始化参数 */
			vprops.put(Velocity.SET_NULL_ALLOWED, "true");
			vprops.put(Velocity.INPUT_ENCODING, "UTF-8");
			vprops.put(Velocity.OUTPUT_ENCODING, "UTF-8");
			vprops.put(Velocity.RESOURCE_LOADER, "classpath");
			vprops.put("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		}
		Velocity.init(vprops);
	}

	/**
	 * 生成模板数据
	 * 
	 * @param context
	 * @param templateName
	 *            模板文件名
	 * @return 返回生成的字符串
	 */
	public static String generateString(VelocityContext context, String templateName) {
		SimpleLog.log("Generating template " + templateName);
		StringWriter sw = new StringWriter();
		context.put("template", new File(templateName).getName());
		Velocity.mergeTemplate(templateName, (String) "UTF-8", (Context) context, (Writer) sw);
		return sw.toString();
	}

	/**
	 * 生成模板数据，写入指定文件
	 * 
	 * @param context
	 * @param templateName
	 *            模板文件名
	 * @param filename
	 *            输出文件名
	 * @throws IOException
	 *             写入文件失败
	 */
	public static void generateFile(VelocityContext context, String templateName, String filename) throws IOException {
		String sql = TemplateGenerator.generateString(context, templateName);
		checkNotNull(Strings.emptyToNull(filename), "filename is null or empty");
		SimpleLog.log(" .... writing to " + filename);
		File file = new File(filename);
		if (file.isAbsolute() && null != file.getParent()) {
			new File(file.getParent()).mkdirs();
		}
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
		// 换行符归一化:所有换行符替换为当前系统的换行符
		String content = Pattern.compile("(\r\n|\n|\r)", Pattern.MULTILINE).matcher(sql)
				.replaceAll(System.getProperty("line.separator"));
		writer.write(content);
		writer.flush();
		writer.close();
		SimpleLog.log("    " + file.getName() + " done.");

	}
}
